const db=require("../db/index")
exports.readblogHandler=(req,res)=>{
    const page=(Number(req.params.page)-1)*5
    var sql="SELECT b.id,b.createtime,b.blogcontent,b.uid,u.avatar,u.username,l.liketotal FROM blog b JOIN user u ON b.uid=u.id LEFT JOIN (SELECT count(*) as liketotal,bid FROM islike GROUP BY bid) l  ON b.id=l.bid ORDER BY b.createtime DESC LIMIT ?,5;"
    db.query(sql,[page],(err,results)=>{
        if(err)return res.R(err)
        if(results.length<=0)return res.R("暂无用户发动态！")
        const csql="select c.commentcontent,c.id,c.uid,c.username,b.id as bid,u.avatar  from comment c join blog b join user u on c.bid=b.id and c.uid=u.id ORDER BY b.createtime DESC"
        db.query(csql,(err,resultcom)=>{
            if (err) return res.R(err)
            if(resultcom.length<=0) return ("评论为空！")
            results.forEach(item1 => {
                item1.comment=[]
                resultcom.forEach(item2 => {
                    if(item1.id===item2.bid)
                    {
                        item1.comment.push(item2)
                    }
                });
            });
            const allsql="select count(*) from blog"
            db.query(allsql,(err,resultsall)=>{
                if (err) return res.R(err)
                 res.send({
                status:200,
                data:results,
                total:resultsall[0]["count(*)"],
                message:"查询动态成功！"
            })
            })
           
        })
       
    })
}
exports.writeBlogHandler=(req,res)=>{
    const id=req.auth.id
    const content=req.fields.content
    var sql="insert into blog set ?"
    db.query(sql,{blogcontent:content,uid:id},(err,results)=>{
        if(err)return res.R(err)
        if (results.affectedRows!==1) return res.R("写入失败！")
        res.send({
            status:200,
            message:"写入成功！"
        })
    })

}

exports.deleteBlogHandler=(req,res)=>{
    const bid=req.params.bid
    const id=req.auth.id
    if(!id)return res.R("身份验证不通过！")
    const sql='delete from blog where id=? and uid = ?'
    db.query(sql,[bid,id],(err,results)=>{
        if (err) return res.R(err)
        if (results.affectedRows!==1) return res.R("删除失败或文章不存在！")
        res.send({
            status:200,
            message:"删除成功！"
        })
    })
}